
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include "tinyramfs.h"
#include "Hamming.h"

#define log(_fmt_, ...)         printf("[TC][%s:%d][%s] "_fmt_"\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__)

static void hexdump(unsigned char *buf, int len, const char *str, ...)
{
    int i, size;
    unsigned short *ptr;

    va_list args;
    va_start(args, str);
    vprintf(str, args);
    va_end(args);

    ptr = (unsigned short *)buf;
    size = (len + 2) / 2;
    for (i = 0; i < size; ++i) {
        if (i % 8 == 0) {
            printf("\n%p:", ptr + i);
        }
        printf(" %04x", ptr[i]);
    }
    printf("\n");
}

int main(int argc, char const *argv[])
{
    int ret;
    unsigned short tag;
    char r_buf[128];
    char w_buf[128];
    const char tst_str[] = "Hello, this is tiny ramfs.";

    init();

    tag = create(0x1102);
    log("tag %#x", tag);
    if (tag == TINYRAMFS_TAG_INVALID) {
        return -1;
    }

    snprintf(w_buf, sizeof(w_buf), "%s This is tag %#x", tst_str, 0x1102);
    log("%s", w_buf);

    ret = write(tag, w_buf, strlen(w_buf));
    log("write %#lx ret %#x", strlen(w_buf), ret);

    dump_data();
    dump_mgr(0, 0x20);

    snprintf(w_buf, sizeof(w_buf), "%s", tst_str);
    log("%s", w_buf);

    ret = write(tag, w_buf, strlen(w_buf));
    log("write %#lx ret %#x", strlen(w_buf), ret);

    dump_data();
    dump_mgr(0, 0x20);

    ret = read(tag, r_buf, sizeof(r_buf));
    log("read ret %#x %.*s", ret, ret, r_buf);

    tag = create(0x1103);
    log("tag %#x", tag);
    if (tag == TINYRAMFS_TAG_INVALID) {
        return -1;
    }

    snprintf(w_buf, sizeof(w_buf), "%s This is tag %#x", tst_str, 0x1103);
    log("%s", w_buf);

    ret = write(tag, w_buf, strlen(w_buf));
    log("write %#lx ret %#x", strlen(w_buf), ret);

    dump_data();

    ret = read(tag, r_buf, 0x20);
    log("read ret %#x %.*s", ret, ret, r_buf);

    ret = delete(0x1102);
    log("delete %#x ret %#x", 0x1102, ret);

    dump_data();

    dump_mgr(0, 0x20);

    // hexdump(g_pool, sizeof(g_pool)>>4, "init done");

    unsigned char val1 = 0x5a, val2 = 0xa5;
    unsigned char ecc;

    ecc = HammingCalculateParity2416(val1, val2);
    log("val1 %#x val2 %#x ecc %#x", val1, val2, ecc);

    val1 ^= 0x38;
    // val2 ^= 0x10;
    log("something err... val1 %#x val2 %#x", val1, val2);

    ret = HammingCorrect2416(&val1, &val2, ecc);
    log("ecc %#x correct ret %d val1 %#x val2 %#x", ecc, ret, val1, val2);

    /* code */
    return 0;
}
